package smartbooks.ui.manager;

import smartbooks.exceptions.MyException;
import smartbooks.ui.SmartBooksUserSettings;
import smartbooks.ui.helper.LoginHelper;
import smartbooks.ui.util.CommonConstants;
import smartbooksdb.hibernatebean.User;
import smartbooksdb.service.UserService;
import smartbooksdb.valuebean.Credentials;

/**
 *
 * @author Ankit
 */
public class LoginManager implements CommonConstants {
    
    /**
     * This method is used to login the user
     * @param credentials
     * @return user
     * @throws MyException
     */
    public static User loginUser(Credentials credentials) throws MyException {
        User user = null;
        
        boolean loginPanelValidated = LoginHelper.validateLogin(credentials);
        
        if(loginPanelValidated) {
            UserService userService = new UserService();
            user = userService.getUser(credentials);
            
            if(null==user) {
                throw new MyException(USERNAME, "Username and Password do not match");
            }
            
            SmartBooksUserSettings.USER_ID = user.getUserId();
            SmartBooksUserSettings.USERNAME = user.getUsername();
            SmartBooksUserSettings.USER_ROLE = user.getRole();
        }
        
        return user;
    }
}
